package com.studyinghome.netty;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.studyinghome.config.NettyConfig;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 自定义处理类
 * TextWebSocketFrame: websocket数据是帧的形式处理
 * <p>
 * ChannelHandler.Sharable //设置通道共享
 *
 * @author leslie
 * @date 2023/03/08
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Autowired
    private NettyConfig nettyConfig;

    public static List<Channel> channelList = new ArrayList<>();


    /**
     * 覆盖了 channelRead0() 事件处理方法。
     * 每当从服务端读到客户端写入信息时， 其中如果你使用的是 Netty 5.x 版本时，
     * 需要把 channelRead0() 重命名为messageReceived()
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (ObjectUtil.isNotNull(msg) && msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;

            log.info("调用 channelRead request.uri() [ {} ]", request.uri());

            String uri = request.uri();
            Map<String, String> paramMap = HttpUtil.decodeParamMap(uri, StandardCharsets.UTF_8);
            if (MapUtil.isNotEmpty(paramMap)) {

//            if (StrUtil.isNotBlank(uri) && StrUtil.containsAll(uri, "/", "?")) {
//                String[] uriArray = uri.split("\\?");
//                if (ArrayUtil.isNotEmpty(uriArray) && uriArray.length > 1) {
//                    String[] paramsArray = uriArray[1].split("=");
//                    if (ArrayUtil.isNotEmpty(paramsArray) && paramsArray.length > 1) {
//                        //截取出链接中携带的参数值
//                        log.info("客户端名称：" + paramsArray[1]);
//                    }
//                }

                log.info("客户端名称：" + paramMap.get("device"));

                request.setUri(nettyConfig.getPath());
            } else {
                log.info("传参格式有问题 ");
                ctx.close();
            }
        }
        super.channelRead(ctx, msg);
    }

    /**
     * 通道就绪事件
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("客户端信息：" + JSON.toJSONString(ctx));

        Channel channel = ctx.channel();
        //当有新的客户端连接的时候, 将通道放入集合
        channelList.add(channel);
        log.info("有新的连接:" + channel.id().toString());
    }


    /**
     * 通道未就绪--channel下线
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("客户端信息：" + JSON.toJSONString(ctx));

        Channel channel = ctx.channel();
        //当有客户端断开连接的时候,就移除对应的通道
        channelList.remove(channel);
        log.info("客户端下线:" + channel.id().toString());
    }

    /**
     * 读就绪事件
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) {
        String msg = textWebSocketFrame.text();
        log.info("msg:" + msg);
        //当前发送消息的通道, 当前发送的客户端连接
        Channel channel = ctx.channel();
        for (Channel channel1 : channelList) {
            //排除自身通道
            if (channel != channel1) {
                channel1.writeAndFlush(new TextWebSocketFrame(msg));
            }
        }
    }

    /**
     * 异常处理事件
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        Channel channel = ctx.channel();
        //移除集合
        channelList.remove(channel);
        log.info("发生异常：" + channel.id().toString());
    }
}
